<template>
  <div class="main">
    <div class="address-container">
    <h1>选择收货地址</h1>
    <div v-if="!isAddress">
      <el-select v-model="order.addressId" placeholder="请选择" style="width: 500px;">
        <el-option
          v-for="item in address"
          :key="item.value"
          :label="item.city+item.address+`      (`+item.name+`收)`+item.phone"
          :value="item.id">
        </el-option>
      </el-select>
    </div>
    <div v-else>
      <h2>你还没有收货地址,请创建</h2>
    </div>
    <el-button type="primary" @click="dialogFormVisible = true">添加地址</el-button>
    <h1>确认订单信息</h1>
    <div>
      <el-table
        :data="orders"
        style="width: 100%">
        <el-table-column
          prop="productInfo"
          label="商品信息"
          width="280">
          <template v-slot="scope">
            <div style="display: flex; align-items: flex-start;">
              <img :src="scope.row.productUrl" alt="" style="width: 60px; height: 60px;">
              <span style="margin-left: 20px;">{{ scope.row.productName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="单价"
          width="180">
        </el-table-column>
        <el-table-column
          prop="quantity"
          label="数量">
          <template v-slot="scope">
            <el-input-number v-model="scope.row.quantity"
              controls-position="right"
              @change="handleChange"
              :min="1" :max="scope.row.number"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column
          prop="subtotal"
          label="小计">
          <template v-slot="scope">
            {{ scope.row.price * scope.row.quantity }}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <p>实付款：</p>
      <span>￥</span>
      <span>{{ totalPayment }}</span>
    </div>
    <br/>
    <el-button type="danger" @click="getOrder">下单</el-button>
    <!-- 添加收货地址 -->
    <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
        <el-form :model="addressForm" :rules="addressFormRules" ref="addressFormRef" label-width="130px">
          <el-form-item label="姓名" prop="name">
              <el-input v-model="addressForm.name"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
              <el-input v-model="addressForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="省市区/县" prop="city">
              <el-cascader collapse-tags="true" :options="cityData" v-model="addressForm.city"></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
              <el-input v-model="addressForm.address"></el-input>
          </el-form-item>
          <el-form-item label="是否为默认地址" prop="isdefault">
              <el-switch
                  v-model="addressForm.isdefault"
                  active-color="#13ce66">
              </el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addAddress">确 定</el-button>
        </div>
    </el-dialog>
    <!-- 支付页面 -->
    <el-dialog
      title="支付"
      :visible.sync="payVisible"
      width="40%">
      <el-tabs v-model="active">
        <el-tab-pane label="微信" name="1">
          <el-image :src="'http://127.0.0.1:8888/image/d97edc79a0434e7280389585a154d820.png'"
          style="width: 50%;height: 450px;"></el-image>
        </el-tab-pane>
        <el-tab-pane label="支付宝" name="2">
          <el-image src="http://127.0.0.1:8888/image/7829de7ace9e4e44884f33a912556b94.jpg"
          style="width: 40%;height: 450px;"></el-image>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer">
        <el-button @click="canel"> 稍后支付 </el-button>
        <el-button type="primary" @click="sure"> 我已支付 </el-button>
      </span>
    </el-dialog>
    </div>
  </div>
</template>

<script>
import cityData from './citydata.js'
import _ from 'lodash'
export default {
    data() {
        return {
          // 订单信息
            userId: 1,
            order: [{
              userId: null,
              productId: null,
              price: null,
              quantity: 1,
              way: '',
              status: '',
              addressId: null
            }],
            // 地址信息
            address: {},
            dialogFormVisible: false,
            addressForm: {
                userid: null,
                name: '',
                phone: '',
                city: '',
                address: '',
                isdefault: ''
            },
            addressFormRules: {
                name: [{ required: true, message: '请输入收件人姓名', trigger: 'blur' },
                { min: 2, max: 10, message: '收件人姓名的长度在2~10个字符之间', teigger: 'blur' }],
                phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' },
                { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的联系电话', trigger: 'blur' }],
                city: [{ required: true, message: '请选择省市区县', trigger: 'blur' }],
                address: [{ required: true, message: '请填写详细地址', trigger: 'blur' }]
            },
            cityData,
            isAddress: false,
            isdefault: true,
            // 页面显示信息
            orders: [{
                productId: null,
                merchantId: null,
                productUrl: '',
                productName: '',
                price: 0,
                quantity: 1,
                subtotal: 0,
                // 默认最大值为 1
                number: 1
            }],
            // 支付的显示
            payVisible: false,
            // 默认微信支付
            active: '1',
            orderId: []
        }
    },
    created() {
      // 获取用户ID
        this.userId = +window.localStorage.getItem('userID')
      // 获取用户地址
        this.getAddress()
      // 获取商品信息
      this.orders = this.$route.query.selectedItems
      this.getProductNum()
    },
    methods: {
        async getAddress() {
            const { data: res } = await this.$axios.get('/address/selectByUserId/' + 5)
            if (res.code !== 200) {
                this.isAddress = true
                return this.$message.error('没有查到你的地址,请创建')
            }
            this.address = res.data.address
        },
        async addAddress() {
            const form = _.cloneDeep(this.addressForm)
            if (this.isdefault) {
                form.isdefault = '是'
            } else {
                form.isdefault = '否'
            }
            form.city = this.addressForm.city.join('')
            form.userid = this.userId
            const { data: res } = await this.$axios.post('/address/add', form)
            if (res.code !== 200) {
                return this.$message.error('创建地址失败,请重试')
            }
            this.$message.success('添加地址成功')
            this.getAddress()
            this.dialogFormVisible = false
        },
        // 获取商品的数量
        async getProductNum() {
          const productIds = this.orders.map(orders => ({
            id: orders.productId
          }))
          const ids = productIds.map(item => item.id)
          console.log('ids : ' + productIds)
            const { data: res } = await this.$axios.post('/product/selectByIds/', ids)
            console.log(res)
            if (res.code !== 200) {
                return this.$message.error('商品不存在！')
            }
            const productMap = {}
            res.data.product.forEach(product => {
              productMap[product.id] = product.number
            })
            this.orders.forEach(order => {
              const number = productMap[order.productId]
              // 检查是否找到了对应的商品信息
              if (number !== undefined) {
                order.number = number
              } else {
                console.log('未找到产品信息')
              }
            })
        },
        // 创建订单
        async getOrder() {
          // 判定收货地址
          if (!this.order.addressId) {
            return this.$message.error('请填写收货地址')
          }
          // 提取购物车的 id
          const cart = this.orders.map(orders => ({
            id: orders.id
          }))
          const orderList = this.orders.map(orders => ({
              userId: this.userId,
              productName: orders.productName,
              productId: orders.productId,
              merchantId: orders.merchantId,
              price: orders.price,
              quantity: orders.quantity,
              way: orders.way,
              status: '未付款',
              addressId: this.order.addressId
          }))
          // 判定商品数量是否小于库存
          const { data: result } = await this.$axios.post('/order/number', orderList)
          if (result.code !== 200) {
            const msg = result.data.msg
            return this.$message.error(`${msg},请稍后下单`)
          }
          console.dir(orderList)
          console.log('order: ' + orderList)
          const { data: res } = await this.$axios.post('/order/add', orderList)
          console.log(res)
          if (res.code !== 200) {
            return this.$message.error('库存不足，订单创建失败')
          }
          // 保存订单id
          this.orders = res.data.order
          this.$message.success('订单创建成功,请支付')
          console.log(cart)
          // 订单创建后，删除购物车对应的内容
          if (cart.length > 0) {
            const ids = cart.map(item => item.id)
            const { data: res } = await this.$axios.post('/shopping-cart/delete', ids)
            console.log(res)
          }
          this.payVisible = true
        },
        // 保存商品数量
        handleChange(newNum) {
          this.order.quantity = newNum
        },
        // 取消支付
        async canel() {
          this.$router.push('/slider/' + 1)
        },
        // 确认支付
        async sure() {
          let way = null
          if (this.active === '1') {
            way = '微信'
          } else {
            way = '支付宝'
          }
          const orderList = this.orders.map(orders => ({
            id: orders.id,
            way: way,
            status: '已付款',
            logisticsNumber: '11111'
          }))
          const { data: res } = await this.$axios.put('/order/update', orderList)
          console.log(res)
          this.payVisible = false
          this.$router.push('/slider/' + 2)
        }
    },
    computed: {
      // 计算商品的实付款
      totalPayment() {
        return this.orders.reduce((total, order) => total + (order.price * order.quantity), 0).toFixed(2)
      }
    }
}
</script>

<style lang="less" scoped>
.address-container {
  width: 1200px;
  margin: 0px auto;
}
.el-button {
  margin: 10px 10px 10px 0px;
}
</style>
